<?php

namespace App\Http\Controllers\Admin;

use App\Common\Service\PassportService;
use App\Http\Controllers\Controller;
use App\Service\AdminService;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    /**
     * 后台登录页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function login()
    {
        return view('admin.login.login');
    }

    /**
     * 登录
     * @param Request $request
     * @return array
     */
    public function signIn(Request $request, PassportService $sms)
    {
        $this->validate($request, [
            'tel' => 'required',
            'code' => 'required'
        ]);
        $service = new AdminService();
        $re = $service->login($request->tel, $request->code, (bool)$request->remember, $sms);
        if ($re) {
            return ApiResponse([]);
        } else {
            return ApiResponse([], $service->getError(), 1);
        }
    }

    /**
     * 登出
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logOut()
    {
        Auth::guard('admin')->logout();
        return redirect('/login');
    }

    /**
     * 生成验证码
     * @param Request $request
     */
    public function captcha() {
        $builder = new CaptchaBuilder();
        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 40, $font = null);
        //获取验证码的内容
        $phrase = $builder->getPhrase();
        session(['loginCaptcha' => $phrase]);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();

    }

    /**
     * 发送短信验证码
     */
    public function sendms(Request $request, PassportService $sms)
    {
        $re = $sms->sendcode($request->input('tel'));
        if (!$re) return ApiResponse([], '发送短信失败', 1);
        return ApiResponse([]);
    }


}
